/******************************************************************
 * Copyright @ 2023 广州牛师帮科技文化有限公司. All rights reserverd.
 * @file   src\hooks\UserPermission.ts
 * @author 朱剑豪
 * @date   2023/10/11 14:44
 * @desc   用于查询当前用户权限
 ******************************************************************/

import { PermissionInfo } from "@nsb/user-center-sso-plugin";
import { useCallback } from "react";
import { useClassList } from "./useClassList";
import { useLocalForageItem } from "./useLocalForage";
import { login_forage } from "./useLoginInfo";

export namespace UserPermission {
  export const ALWAYS_OFF: string = '__always_denied__'
  // export const DEVELOPING: string = __ENV__ === 'stage' ? '' : '__always_granted_on_env_stage__'
  export const DEVELOPING: string = ''//__ENV__ === 'stage' ? '' : '__always_granted_on_env_stage__'

  /**
   * 检查权限情况的函数
   *
   * @export
   * @interface PermissionChecker
   */
  export interface PermissionChecker {
    /**
     * 是否存在指定名称的权限
     *
     * @param {string} [permissions] 权限名称，当需要多个时，都好分隔
     * @return {boolean} 当全部权限都存在时，返回true, 否则返回false
     * @memberof PermissionChecker
     */
    (permissions?: string): boolean;
  };

  /**
   * react hook函数：获取一个检查权限情况的函数
   * 用法：
   *    const checkPermission = UserPermission.use();
   *    const hasPermission:boolean = checkPermission("特定权限0,特定权限1")
   *
   * @return {PermissionChecker} 检查权限情况的函数
   */
  export function use(): PermissionChecker {
    const is_dev = useClassList(document.body)?.some(v => v === 'dev') === true;
    const [granteds] = useLocalForageItem<PermissionInfo[]>({ storage: login_forage, key: 'permissions' })
    return useCallback((permissions?: string) => {
      if (permissions === void 0 || permissions == null) return true;
      if (permissions === "") return granteds !== null;
      const requires = permissions?.split(',').filter(v => v);
      if (!requires?.length) { return true; }
      for (let i = 0; i < requires.length; ++i) {
        const permission = requires[i];
        if (is_dev && permission === 'developing') continue;
        if (permission === ALWAYS_OFF) { return false }
        return !!granteds?.some(v => v.name === permission)
      }
      return true;
    }, [granteds, is_dev])
  }

  /**
   * 获取权限信息列表
   *
   * @export
   * @return {(PermissionInfo[] | null)} 当未登录时，返回null，否则返回获取权限信息列表
   */
  // export function get(): PermissionInfo[] | null {
  //   const rawStr = LiveStorage.get('expiry_local').getItem('permissions');
  //   if (!rawStr) {
  //     return null;
  //   }
  //   try {
  //     return JSON.parse(rawStr)
  //   } catch (e) {
  //     return null
  //   }
  // }
}